Flask session
A Flask session can be defined as data temporarily stored on a Flask server for the duration in which a user logs into a Flask server, and logs out. The session data is stored on top of cookies and signed by the server cryptographically.
templates\template.html
{% if time is defined %}
<p>Session commenced at: {{time}}</p>
<a href="/stop_session">stop session</a>
{% else %}
<a href="/start_session">start session</a>
{% endif %}
server.py
from flask import *
from datetime import *
app = Flask("sessions in flask")
#session in Flask requires any secret key.
#this key encrypts cookies sent to browser.
#normally this lives outside of this file:
app.secret_key = "password1234"
@app.route("/")
def main():
if "time_started" in session:
return render_template("template.html",
time=session["time_started"])
else:
return render_template("template.html")
@app.route("/start_session")
def start_session():
if "time_started" not in session:
right_now = datetime.now()
time_formatted = right_now.strftime("%A, %d %B %Y, %H:%M:%S")
session["time_started"] = time_formatted
return redirect("/")
@app.route("/stop_session")
def stop_session():
if "time_started" in session:
session.pop("time_started")
return redirect("/")
app.run(debug=True)